package com.jinzhi.jzweb.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.base.CoreServiceImpl;
import com.jinzhi.common.constants.ConstMessages;
import com.jinzhi.common.constants.MessagesEnum;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.ShiroUtils;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzapi.utils.JWTUtil;
import com.jinzhi.jzweb.dao.JazUserHouseDao;
import com.jinzhi.jzweb.domain.JazMessageDO;
import com.jinzhi.jzweb.domain.JazSysProjectDO;
import com.jinzhi.jzweb.domain.JazUserAuntDO;
import com.jinzhi.jzweb.domain.param.UserHouseQuery;
import com.jinzhi.jzweb.domain.JazUserHouseDO;
import com.jinzhi.jzweb.domain.vo.JazUserHouseVO;
import com.jinzhi.jzweb.service.JazMessageService;
import com.jinzhi.jzweb.service.JazSysProjectService;
import com.jinzhi.jzweb.service.JazUserAuntService;
import com.jinzhi.jzweb.service.JazUserHouseService;
import com.jinzhi.sys.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/***
 * @author ChangPanYuan
 * @Date 2024/5/10
 * @Description: 用户住宿
 * @Version 1.0
 */
@Service
public class JazUserHouseServiceImpl extends CoreServiceImpl<JazUserHouseDao, JazUserHouseDO> implements JazUserHouseService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private JazSysProjectService jazSysProjectService;

    @Autowired
    private JazUserAuntService jazUserAuntService;

    @Autowired
    private JazMessageService jazMessageService;

    /**
     * 分页查询住宿列表
     *
     * @param userHouseQuery
     * @return
     */
    @Override
    public Page<JazUserHouseDO> getUserHousePage(UserHouseQuery userHouseQuery) {
        Page<JazUserHouseDO> page = new Page<>(
                Optional.of(userHouseQuery.getCurr()).orElse(1),
                Optional.of(userHouseQuery.getPageSize()).orElse(10));
        Wrapper wrapper  = new EntityWrapper().
                like(StringUtil.notEmpty(userHouseQuery.getUsername()),"username",userHouseQuery.getUsername()).
                eq(Objects.nonNull(userHouseQuery.getAuditStatus()),"audit_status",userHouseQuery.getAuditStatus())
                .orderBy("create_time",false);
        Page<JazUserHouseDO> jazUserAunts =  selectPage(page,wrapper);

        //查询项目类型
        List<String> projectIds = jazUserAunts.getRecords().stream().filter(a ->Objects.nonNull(a.getProjectId()))
                .map(JazUserHouseDO::getProjectId).distinct().collect(Collectors.toList());
        if(ObjectUtils.isEmpty(projectIds)){
            return jazUserAunts;
        }
        List<String> projectIds1 = new ArrayList<>();
        for (int i = 0; i < projectIds.size(); i++) {
            projectIds1.addAll(Arrays.asList(projectIds.get(i).split(",")));
        }
        List<JazSysProjectDO>  jazSysProjectDOS = jazSysProjectService.selectList(new EntityWrapper<JazSysProjectDO>().in("id",projectIds1));
        jazUserAunts.getRecords().forEach(a-> {
            a.setProjectName(jazSysProjectDOS.stream().filter(b -> Objects.nonNull(a.getProjectId())).
                    filter(b -> a.getProjectId().contains(b.getId().toString())).
                    map(JazSysProjectDO::getName).collect(Collectors.joining(",")));
        });

        return jazUserAunts;
    }

    /**
     * 新增住宿
     *
     * @param userHouseDO
     * @return
     */
    @Override
    public Result<String> insertUserHouse(JazUserHouseDO userHouseDO) {
        if (userHouseDO==null){
            return Result.fail();
        }
        // 获取用户信息
        UserDO userDO = userDao.selectById(userHouseDO.getSysUserid());
        if (userDO!=null){
            // 获取手机号码
            userHouseDO.setPhone(userDO.getMobile());
            userHouseDO.setUsername(userDO.getName());
        }
        // 获取项目类型
        Wrapper<JazUserAuntDO> wrapper = new EntityWrapper<JazUserAuntDO>().eq("sys_userid", userHouseDO.getSysUserid());
        JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(wrapper);
        if (jazUserAuntDO!=null) {
            userHouseDO.setProjectId(jazUserAuntDO.getProjectId());
            if (StringUtil.notEmpty(userHouseDO.getProjectId())) {
                String[] projects = userHouseDO.getProjectId().split(",");
                List<JazSysProjectDO> jazSysProjectDOS = jazSysProjectService.selectList(new EntityWrapper<JazSysProjectDO>().in("id", projects));
                userHouseDO.setProjectName(jazSysProjectDOS.stream().map(JazSysProjectDO::getName).collect(Collectors.joining(",")));

            }
        }
        userHouseDO.setAuditStatus(0);
        userHouseDO.setAuditResult(2);
        Integer insert = this.baseMapper.insert(userHouseDO);
        return insert==0?Result.fail():Result.ok();
    }

    /**
     * 根据id删除用户信息
     *
     * @param id
     * @return
     */
    @Override
    public Result<Object> deletedById(Long id) {
        if (id==null){
            return Result.fail();
        }
        boolean b = this.deleteById(id);
        return b?Result.ok():Result.fail();
    }

    /**
     * 根据id查询住宿详情
     *
     * @param id
     * @return
     */
    @Override
    public JazUserHouseDO getUserHouseById(Long id) {
        if (id == null){
            return null;
        }
        JazUserHouseDO jazUserHouseDO = this.selectById(id);
        // 查询项目类型
        if (StringUtil.notEmpty(jazUserHouseDO.getProjectId())){
            String[] projects = jazUserHouseDO.getProjectId().split(",");
            List<JazSysProjectDO>  jazSysProjectDOS = jazSysProjectService.selectList(new EntityWrapper<JazSysProjectDO>().in("id",projects));
            jazUserHouseDO.setProjectName(jazSysProjectDOS.stream().map(JazSysProjectDO::getName).collect(Collectors.joining(",")));
        }
        return jazUserHouseDO;
    }

    /**
     * 修改住宿审核信息
     *
     * @param jazUserHouseDO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result updateExamineHouse(JazUserHouseDO jazUserHouseDO) {
        JazUserHouseDO userHouseDO = this.selectById(jazUserHouseDO.getId());
        if (userHouseDO == null){
            return  Result.fail();
        }
        // 判断审核结果是不是通过
        if (jazUserHouseDO.getAuditResult()==0){
            userHouseDO.setAuditStatus(1);
            userHouseDO.setAuditResult(0);
        } else if (jazUserHouseDO.getAuditResult()==1) {
            userHouseDO.setAuditStatus(1);
            userHouseDO.setAuditResult(1);
            userHouseDO.setRefuseReason(jazUserHouseDO.getRefuseReason());
        }
        boolean update = this.updateById(userHouseDO);
        // 发送审核消息
        if (userHouseDO.getAuditResult()==0){
            // 通过
            JazMessageDO jazMessageDO1 = new JazMessageDO();
            jazMessageDO1.setMessageType(1);
            jazMessageDO1.setSenderId(ShiroUtils.getUserId());
            jazMessageDO1.setReceiverId(userHouseDO.getSysUserid());
            jazMessageDO1.setMessageContent(MessagesEnum.MESSAGE_105.getMsg());
            jazMessageDO1.setMessageNum(MessagesEnum.MESSAGE_105.getNum());
//            jazMessageDO1.setObjectId(userHouseDO.getId());
            jazMessageDO1.setIsRead(0);
            jazMessageService.senMessage(jazMessageDO1);
        } else if (userHouseDO.getAuditResult()==1) {
            // 拒绝
            JazMessageDO jazMessageDO1 = new JazMessageDO();
            jazMessageDO1.setMessageType(1);
            jazMessageDO1.setSenderId(ShiroUtils.getUserId());
            jazMessageDO1.setReceiverId(userHouseDO.getSysUserid());
            jazMessageDO1.setMessageContent(MessagesEnum.MESSAGE_106.getMsg()+userHouseDO.getRefuseReason());
            jazMessageDO1.setMessageNum(MessagesEnum.MESSAGE_106.getNum());
//            jazMessageDO1.setObjectId(userHouseDO.getId());
            jazMessageDO1.setIsRead(0);
            jazMessageService.senMessage(jazMessageDO1);
        }
        return update?Result.ok():Result.fail();
    }

    /**
     * 修改住宿信息
     *
     * @param jazUserHouseDO
     * @return
     */
    @Override
    public Result updateHouse(JazUserHouseDO jazUserHouseDO) {
        if (jazUserHouseDO == null){
            return Result.fail();
        }
        boolean update = this.updateById(jazUserHouseDO);
        return update?Result.ok():Result.fail();
    }

    /**
     * 阿姨端 预约入住
     * @param userHouseDO
     * @return
     */
    @Override
    public Result<?> auntSubscribeHouse(JazUserHouseDO userHouseDO) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        //参数校验
        Assert.notNull(userHouseDO,"参数异常");
        Assert.notNull(userHouseDO.getUsername(),"请输入姓名");
        Assert.notNull(userHouseDO.getSex(),"请选择性别");
        Assert.notNull(userHouseDO.getPhone(),"请输入联系方式");
        Assert.notNull(userHouseDO.getMovieHouseTime(),"请选择入住时间");
        //入住时间要大于当前时间
//        String movieHouseTim = sf.format(userHouseDO.getMovieHouseTime());
        String nowDate = sf.format(new Date());
        if (nowDate.compareTo(userHouseDO.getMovieHouseTime())==1) {
            return Result.fail("入住时间不得小于当前时间");
        }

        Long userId = JWTUtil.getUser().getId();
        userHouseDO.setSysUserid(userId);
        Wrapper<JazUserAuntDO> wrapper = new EntityWrapper<JazUserAuntDO>().eq("sys_userid",userId);
        JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(wrapper);
        if (jazUserAuntDO!=null) {
            userHouseDO.setProjectId(jazUserAuntDO.getProjectId());
            if (StringUtil.notEmpty(userHouseDO.getProjectId())) {
                String[] projects = userHouseDO.getProjectId().split(",");
                List<JazSysProjectDO> jazSysProjectDOS = jazSysProjectService.selectList(new EntityWrapper<JazSysProjectDO>().in("id", projects));
                userHouseDO.setProjectName(jazSysProjectDOS.stream().map(JazSysProjectDO::getName).collect(Collectors.joining(",")));

            }
        }
        userHouseDO.setAuditStatus(0);
        userHouseDO.setAuditResult(2);
        Integer insert = this.baseMapper.insert(userHouseDO);
        return insert==0?Result.fail():Result.ok();
    }

    /**
     * 阿姨预约入住详情
     * @return
     */
    @Override
    public JazUserHouseDO auntGetHouse() {
        JazUserHouseDO jazUserHouseDO = new JazUserHouseDO();
        Long userId = JWTUtil.getUser().getId();
        //查询用户最新的一条入住信息
        List<JazUserHouseDO> jazUserHouseDOS = this.selectList(new EntityWrapper<JazUserHouseDO>().eq("sys_userid", userId).orderBy("create_time", false));
        if(null!=jazUserHouseDOS && !jazUserHouseDOS.isEmpty()){
            jazUserHouseDO = jazUserHouseDOS.get(0);
        }


        return jazUserHouseDO;
    }

}
